<script setup lang="ts">
import * as echarts from 'echarts';
import SkyUploadFile from "@/components/SkyUpload/file.vue";
import {useRoute} from "vue-router";
import {useSkyDept, useSkyDeptObj} from "@/hooks/dept";
import {useSkyDict} from "@/hooks/dict";
import {useScreenStore} from "@/hooks/screen";
import {fieldVisible, getCurrentDateTime} from "@/utils";
import {skyNoticeSuccess, skyNoticeError, skyMsgError, skyMsgWarning, skyMsgBox, skyMsgInfo, skyMsgSuccess} from "@/utils/sky.js";
import {
  exportExcel,
  deleteById,
  batchDelete,
  update,
  getStatistics,
  listPage,
  getById,
} from "@/apis/sky/tools/bucket/detail";
import {DArrowLeft, Warning} from "@element-plus/icons-vue";

const route = useRoute();
// 获取当前为[移动端、IPad、PC端]仓库，阔以使用 watchEffect(() => {}) 进行监听。
const {isScreen} = useScreenStore();
/** 适配移动端结束 */
const {skyDept} = useSkyDept();
const {skyDict} = useSkyDict(["状态", "文件分类"]);
const skyFileRef = ref();
const skyDialogRef = ref();
const treeRef = ref();
const formRef = ref();
const pageData = ref({
  props: {children: "children", label: "name"},
  showSearch: true,
  pageParams: {
    creator: null,
    modifier: null,
    status: true,
    name: "",
    type: "",
    suffix: "",
    bucket_id: route.params.params,
    page: 1,
    pageSize: 10,
  },
  ids: [],
  single: true,
  multiple: true,
  title: "本地存储",
  confirmLoading: false,
  mobile: false,
  isTree: true,
  form: {
    id: null,
    rename: null,
    size: 0,
    suffix: "",
    path: "",
    url: "",
    sort: 1,
    status: true,
    belong_dept: null,
    remark: null,
  },
  rules: {
    rename: [{required: true, message: "请输入文件名称", trigger: "blur"}],
  },
  loading: false,
  total: 0,
  size: 0,
  showTable: [
    {title: "文件原名", visible: 1},
    {title: "文件重命名", visible: 1},
    {title: "原文件大小", visible: 1},
    {title: "原文件后缀", visible: 1},
    {title: "文件分类", visible: 1},
    {title: "项目根目录", visible: 1},
    {title: "文件绝对路径", visible: 1},
    {title: "文件所在路径", visible: 1},
    {title: "文件地址", visible: 1},
    {title: "存储桶名称", visible: 1},
  ],
  statistics: {
    totalSize: 0,
    totalQuantity: 0,
    statistics: [],
  },
  tableList: [],
});
const method = reactive({
  /** 选择文件分类树 */
  handleCurrentChange: (val: any) => {
    pageData.value.pageParams.type = val.value === "1" ? "" : val.value;
    pageData.value.pageParams.page = 1;
    pageData.value.pageParams.pageSize = 10;
    method.handleListPage();
  },
  /** 显示树或隐藏树 */
  handleIsTreeOrTable: () => {
    setTimeout(() => {
      pageData.value.mobile = !pageData.value.mobile;
      pageData.value.isTree = !pageData.value.isTree;
    }, 500);
    skyMsgSuccess("切换成功");
  },
  /** 搜索 */
  handleSearch: () => {
    pageData.value.pageParams.page = 1;
    pageData.value.pageParams.pageSize = 10;
    method.handleListPage();
  },
  /** 重置 */
  resetSearch: () => {
    method.resetSearchParams();
    method.handleListPage();
    // method.handleStatistics();
  },
  /** 重置搜索参数 */
  resetSearchParams: () => {
    pageData.value.pageParams = {
      creator: null,
      modifier: null,
      status: true,
      name: "",
      type: "",
      suffix: "",
      bucket_id: route.params.params,
      page: 1,
      pageSize: 10,
    };
    // 清空状态
    treeRef.value.skyClearChecked();
  },
  /** 上传文件 */
  handleImportFile: () => {
    let params = {
      title: "上传文件🌻",
      isApi: true, // 是否后台上传
      importApi: "/sky/tools/uploadFile/batch/" + route.params.params,
    };
    skyFileRef.value.uploadParams(params);
  },
  /** 文件上传回调 */
  handleConfirmUpload: () => {
    method.handleListPage();
    method.handleStatistics();
  },
  /** 删除 */
  handleDelete: (row: any) => {
    const id = row.id;
    if (id === null || id === "") {
      skyMsgWarning("请选中需要删除的数据🌻");
      return;
    }
    skyMsgBox("您确认需要删除名称[" + row.name + "]么？")
      .then(async () => {
        try {
          await deleteById(id);
          await method.handleListPage();
          await method.handleStatistics();
          skyNoticeSuccess("删除成功🌻");
        } catch (error) {
          await method.handleListPage();
          await method.handleStatistics();
          skyNoticeError("删除失败，请刷新重试🌻");
        }
      })
      .catch(() => {
        skyMsgError("已取消🌻");
      });
  },
  /** 批量删除 */
  handleBatchDelete: () => {
    if (pageData.value.ids.length == 0) {
      skyMsgInfo("请选择需要删除的数据🌻");
      return;
    }
    skyMsgBox("您确认需要进行批量删除么？")
      .then(async () => {
        try {
          const res: any = await batchDelete(pageData.value.ids);
          await method.handleListPage();
          await method.handleStatistics();
          skyNoticeSuccess(`${res.msg}`);
        } catch (error) {
          await method.handleListPage();
          skyNoticeSuccess("批量删除失败，请刷新重试🌻");
        }
      })
      .catch(() => {
        skyMsgError("已取消🌻");
      });
  },
  /** 修改 */
  handleUpdate: (row: any) => {
    // 打开弹出框
    skyDialogRef.value.skyOpen();
    // 重置表单
    method.resetForm();
    pageData.value.title = "修改";
    const id = row ? row.id : pageData.value.ids[0];
    if (id == null || id === "") {
      skyMsgError("请选中需要修改的数据🌻");
    }
    // 回显数据
    method.handleEcho(id);
  },
  /** 回显数据 */
  handleEcho: async (id: any) => {
    if (id === null || id === "") {
      skyMsgWarning("请选择需要修改的数据🌻");
      return;
    }
    try {
      const res = await getById(id);
      pageData.value.form = res.data;
      pageData.value.form.rename = res.data.rename.split(".")[0];
    } catch (error) {
      skyNoticeError("数据获取失败，请刷新重试🌻");
    }
  },
  /** 确定  */
  handleConfirm: () => {
    if (!formRef.value) return;
    pageData.value.confirmLoading = true;
    (formRef.value).validate(async (valid: any) => {
      if (valid) {
        if (pageData.value.form.id) {
          try {
            await update(pageData.value.form.id, pageData.value.form);
            skyNoticeSuccess("修改成功🌻");
            pageData.value.confirmLoading = false;
            skyDialogRef.value.skyQuickClose();
            method.resetForm();
            await method.handleListPage();
          } catch (error) {
            pageData.value.confirmLoading = false;
            skyNoticeError("修改失败，请刷新重试🌻");
          }
        }
      } else {
        skyMsgError("验证失败，请检查填写内容🌻");
        pageData.value.confirmLoading = false;
      }
    });
  },
  /** 取消 */
  handleCancel: () => {
    skyDialogRef.value.skyClose();
  },
  /** 清空表单数据 */
  resetForm: () => {
    nextTick(() => {
      if (formRef.value) {
        // 重置该表单项，将其值重置为初始值，并移除校验结果
        formRef.value.resetFields();
      }
    });
    pageData.value.form = {
      id: null,
      rename: null,
      size: 0,
      suffix: "",
      path: "",
      url: "",
      sort: 1,
      status: true,
      belong_dept: null,
      remark: null,
    };
  },
  /** 导出 */
  handleDownload: async () => {
    const res: any = await exportExcel();
    const blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
    const dom = document.createElement('a');
    const downUrl = window.URL.createObjectURL(blob);
    dom.href = downUrl;
    dom.download = `${route.meta.title}[${getCurrentDateTime()}]表报`;
    dom.style.display = 'none';
    document.body.appendChild(dom);
    dom.click();
    dom.parentNode.removeChild(dom);
    window.URL.revokeObjectURL(downUrl);
    skyMsgSuccess("导出成功🌻");
  },
  /** 是否多选 */
  handleSelectionChange: (selection: any) => {
    pageData.value.ids = selection.map((item: any) => item.id);
    pageData.value.single = selection.length !== 1; // 单选
    pageData.value.multiple = !selection.length; // 多选
  },
  /** 数据表格 */
  handleListPage: async () => {
    try {
      pageData.value.loading = true;
      pageData.value.tableList = [];
      const res: any = await listPage(pageData.value.pageParams);
      pageData.value.total = res.data.total;
      pageData.value.tableList = res.data.items;
      pageData.value.loading = false;
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
  /** 获取文件类型统计 */
  handleStatistics: async () => {
    try {
      pageData.value.statistics = {
        totalSize: 0,
        totalQuantity: 0,
        statistics: [],
      };
      const res: any = await getStatistics(pageData.value.pageParams);
      pageData.value.statistics = res.data;
      method.handleInitChart(res.data.statistics);
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
  /** 初始化图表 */
  handleInitChart: (data: any) => {
    let chartDom = document.getElementById('main');
    let myChart = echarts.init(chartDom);
    let option;
    option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      series: [
        {
          name: '本地存储统计',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 40,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: data,
        }
      ]
    };
    option && myChart.setOption(option);
  },
});
onMounted(() => {
  pageData.value.mobile = isScreen.value;
  method.handleListPage();
  method.handleStatistics();
});
</script>

<template>
  <div class="sky-flex">
    <div v-if="pageData.isTree" class="treeList sky-flex mr2">
      <SkyCard>
        <!-- 数据字典 -->
        <SkyTree
          ref="treeRef"
          tree-name="文件类型"
          :props="pageData.props"
          :treeData="skyDict['文件分类']"
          node-key="name"
          @currentChange="method.handleCurrentChange"
        />
        <!-- 文件统计 -->
        <div class="statistic-card">
          <el-statistic :value="pageData.statistics.totalSize">
            <template #title>
              <div style="display: inline-flex; align-items: center">
                储存量(MB)
                <el-tooltip
                  effect="dark"
                  content="文件总大小"
                  placement="top"
                >
                  <el-icon style="margin-left: 4px" :size="12">
                    <Warning/>
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-statistic>
          <el-divider style="height: 100%" direction="vertical"></el-divider>
          <el-statistic :value="pageData.statistics.totalQuantity">
            <template #title>
              <div style="display: inline-flex; align-items: center">
                数量
                <el-tooltip
                  effect="dark"
                  content="文件总数量"
                  placement="top"
                >
                  <el-icon style="margin-left: 4px" :size="12">
                    <Warning/>
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-statistic>
        </div>
        <div id="main" style="height: 350px;"></div>
        <!-- 显示表格 -->
        <div v-if="pageData.mobile" class="right">
          <el-tooltip content="显示表格" placement="top">
            <el-button circle icon="DArrowRight" @click="method.handleIsTreeOrTable"/>
          </el-tooltip>
        </div>
      </SkyCard>
    </div>
    <div v-if="!pageData.mobile" class="tableList sky-flex">
      <SkyCard>
        <!-- 搜索条件 -->
        <el-form v-show="pageData.showSearch" :inline="true" label-width="80px">
          <el-form-item label="文件原名" prop="name">
            <el-input
              style="width: 240px"
              placeholder="请输入文件原名"
              v-model="pageData.pageParams.name"
              clearable
              @keyup.enter.native="method.handleSearch"
            ></el-input>
          </el-form-item>
          <el-form-item label="文件后缀" prop="suffix">
            <el-input
              style="width: 240px"
              placeholder="请输入文件后缀"
              v-model="pageData.pageParams.suffix"
              clearable
              @keyup.enter.native="method.handleSearch"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="pageData.pageParams.status" style="width: 240px" clearable>
              <el-option label="启用" :value="true"/>
              <el-option label="禁用" :value="false"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" plain v-throttle="method.handleSearch">搜索</el-button>
            <el-button type="danger" icon="refresh" plain v-debounce="method.resetSearch">重置</el-button>
            <el-button v-if="isScreen" circle @click="method.handleIsTreeOrTable">
              <template #icon>
                <el-tooltip content="显示数据字段" placement="top">
                  <el-icon>
                    <DArrowLeft/>
                  </el-icon>
                </el-tooltip>
              </template>
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 表格头部按钮 -->
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="primary" icon="Upload" plain @click="method.handleImportFile()">上传</el-button>
            <!-- 文件上传 -->
            <SkyUploadFile ref="skyFileRef" @handleConfirmUpload="method.handleConfirmUpload"></SkyUploadFile>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="delete" plain @click="method.handleBatchDelete()" :disabled="pageData.multiple">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="edit" plain @click="method.handleUpdate(null)" :disabled="pageData.single">
              修改
            </el-button>
          </el-col>
        </el-row>
        <br/>
        <!-- 表格头部按钮 -->
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button type="warning" icon="download" plain @click="method.handleDownload">导出</el-button>
          </el-col>
          <SkyToolbar v-model:showSearch="pageData.showSearch" v-model:showColumns="pageData.showTable"
                      @refreshTable="method.handleListPage"></SkyToolbar>
        </el-row>
        <br/>
        <!-- 数据表格 -->
        <el-table
          v-loading="pageData.loading"
          border
          :data="pageData.tableList"
          empty-text="暂时没有数据哟🌻"
          @selection-change="method.handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" fixed="left"/>
          <el-table-column label="主键ID" prop="id" width="110" align="center"/>
          <el-table-column v-if="fieldVisible('文件原名', pageData.showTable)" label="文件原名" prop="name"
                           width="150" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              <a :href="scope.row.url" target="_blank">{{ scope.row.name }}</a>
            </template>
          </el-table-column>
          <el-table-column v-if="fieldVisible('文件重命名', pageData.showTable)" label="文件重命名" prop="rename"
                           width="150" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              <a :href="scope.row.url" target="_blank">{{ scope.row.rename }}</a>
            </template>
          </el-table-column>
          <el-table-column v-if="fieldVisible('原文件大小', pageData.showTable)" label="原文件大小(MB)" prop="size"
                           width="150" align="center" :show-overflow-tooltip="true"/>
          <el-table-column v-if="fieldVisible('原文件后缀', pageData.showTable)" label="原文件后缀" prop="suffix"
                           width="150" align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column v-if="fieldVisible('文件分类', pageData.showTable)" label="文件分类" prop="type"
                           width="150" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              <SkyTag :tagOptions="skyDict['文件分类']" :value="scope.row.type"></SkyTag>
            </template>
          </el-table-column>
          <el-table-column v-if="fieldVisible('项目根目录', pageData.showTable)" label="项目根目录" prop="baseDir"
                           width="150" align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column v-if="fieldVisible('文件绝对路径', pageData.showTable)" label="文件绝对路径" prop="fileDir"
                           width="150" align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column v-if="fieldVisible('文件所在路径', pageData.showTable)" label="文件所在路径" prop="path"
                           width="150" align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column v-if="fieldVisible('文件地址', pageData.showTable)" label="文件地址" prop="url"
                           width="150" align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column v-if="fieldVisible('存储桶名称', pageData.showTable)" label="存储桶名称" prop="bucket"
                           width="150" align="center" :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="状态" prop="status" width="150" align="center" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="启用"
                inactive-text="禁用"
              />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="200" align="center"
                           :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="排序" prop="sort" width="100" align="center"
                           :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="数据归属部门" prop="belong_dept" width="170" align="center"
                           :show-overflow-tooltip="true">
            <template #default="scope">
              {{ useSkyDeptObj(skyDept.dept, scope.row.belong_dept) }}
            </template>
          </el-table-column>
          <el-table-column label="创建人" prop="creator" width="150" align="center"
                           :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="修改人" prop="modifier" width="150" align="center"
                           :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="创建时间" prop="create_time" width="180" align="center"
                           :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="修改时间" prop="update_time" width="180" align="center"
                           :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="操作" align="center" width="120" fixed="right">
            <template #default="{ row }">
              <el-tooltip content="修改🌻" placement="top">
                <el-button
                  type="primary"
                  icon="Edit"
                  circle
                  plain
                  @click="method.handleUpdate(row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除🌻" placement="top">
                <el-button
                  type="danger"
                  icon="Delete"
                  circle
                  plain
                  @click="method.handleDelete(row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <br/>
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="pageData.pageParams.page"
          v-model:page-size="pageData.pageParams.pageSize"
          v-show="pageData.total > 0"
          background
          :page-sizes="[10, 20, 50, 100, 200]"
          :layout="isScreen?'total, sizes, jumper':'total, sizes, prev, pager, next, jumper'"
          :total="pageData.total"
          @size-change="method.handleListPage"
          @current-change="method.handleListPage"
        />
        <!-- 添加 OR 修改 -->
        <SkyDialog
          ref="skyDialogRef"
          :title="pageData.title"
          @skyConfirm="method.handleConfirm"
          @skyCancel="method.handleCancel"
          :loading="pageData.confirmLoading"
          :height="380"
        >
          <template #content>
            <el-form ref="formRef" :rules="pageData.rules" :model="pageData.form" label-width="auto" status-icon>
              <el-row>
                <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                  <el-form-item label="文件重命名" prop="rename">
                    <el-input v-model="pageData.form.rename" placeholder="请输入文件重命名"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                  <el-form-item label="文件大小" prop="size">
                    <el-input-number style="width: 100%" v-model="pageData.form.size" disabled clearable/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                  <el-form-item label="文件后缀" prop="suffix">
                    <el-input v-model="pageData.form.suffix" placeholder="请输入文件后缀" disabled clearable/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                  <el-form-item label="文件所在路径" prop="path">
                    <el-input v-model="pageData.form.path" placeholder="请输入文件所在路径" disabled clearable/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                  <el-form-item label="文件地址" prop="url">
                    <el-input v-model="pageData.form.url" placeholder="请输入文件地址" disabled clearable/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="pageData.form.remark" :rows="4" type="textarea" placeholder="请输入备注"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </template>
        </SkyDialog>
      </SkyCard>
    </div>
  </div>
</template>

<style scoped lang="scss">
.sky-flex {
  flex-direction: row;

  .treeList {
    position: relative;
    width: 18%;
    display: flex;
    flex-direction: column;

    .statistic-card {
      margin-top: 50px;
      display: flex;
      justify-content: space-between;
    }

    .right {
      position: absolute;
      bottom: 20px;
      right: 20px;
    }
  }

  .tableList {
    width: 82%;
  }

  .formTree {
    width: 23%;
  }

  .form {
    width: 77%;
  }
}
</style>
